<script lang="ts" setup>
import { storeToRefs } from 'pinia'
import { getDetailWallApi, getDownloadWallApi, getSetupScoreApi, getUserWallListApi, getWallListApi } from '@/api/index'
import { useWallStore } from '@/store'
import { number } from '@/uni_modules/uv-ui-tools/libs/function/test'
import { capsuleButtonHeight, safeAreaInsets } from '@/utils/systemInfo'
import {
  getCurrentDate,
  getCurrentTime,
  goHome,
} from '@/utils/utils'

definePage({
  style: {
    navigationBarTitleText: '预览',
    navigationStyle: 'custom',
  },
})

let { classificationName, classList, classListTotal, user } = storeToRefs(useWallStore())
let wallList = ref([])
let wallIndex = ref(1)
let wallData = ref(null)
let maskFlag = ref(true) // 全屏显示
let msgPopup = ref(null)// 信息弹框的显示隐藏
let isScoreFlag = ref(false)// 是否评分
let scoringCount = ref(0)// 分数
let scoringPopup = ref(null)// 评分弹框
let userType = ref('')// userType
const heightComputed = computed(() => {
  let height
  // #ifdef MP-WEIXIN
  height = `calc(100vh - ${safeAreaInsets?.bottom}px)`
  // #endif

  // #ifndef MP-WEIXIN
  height = `100vh`
  // #endif

  return height
})
function maskClick() {
  maskFlag.value = !maskFlag.value
}
function maskChange(e) {
  wallIndex.value = e.current
  wallData.value = classList.value[e.current]
  // 判断是否评分过
  if (wallData.value.userScore) {
    isScoreFlag.value = true
    scoringCount.value = wallData.value.userScore
  }
  else {
    scoringCount.value = 0
  }
  console.log(e.current + 2, classListTotal.value, e.current + 2, classList.value.length, '222e.current + 1 !== classListTotal.value && e.current + 1 === classList.value.length')

  // 发送请求
  // if (e.current + 1 !== classListTotal.value && e.current === classList.value.length - 1) {
  //   getWallList()
  // }
}
async function getWallList() {
  let val
  let params = { pageNum: Math.floor(classList.value.length / 9) + 1, pageSize: 9 }
  if (userType.value) {
    val = await getUserWallListApi({ ...params, type: userType.value })
  }
  else {
    val = await getWallListApi({ ...params, classid: wallData.value.classid })
  }

  if (val.length) {
    classList.value.push(...val.map((item, index) => {
      return { ...item, picurl: item.smallPicurl.replace('_small.webp', '.jpg') }
    }))
  }
}
function popOpen() {
  msgPopup.value.open()
}
function closePopup() {
  msgPopup.value.close()
}
function scoringHandler() {
  isScoreFlag.value = false
  if (wallData.value.userScore) {
    isScoreFlag.value = true
  }
  scoringPopup.value.open()
}
function closeScoringPopup() {
  scoringPopup.value.close()
}
function scoringSubmitHandler() {
  getSetupScoreApi({ classid: wallData.value.classid, userScore: scoringCount.value.toString(), wallId: wallData.value._id }).then((res) => {
    if (res) {
      uni.showToast({ title: '评分成功', icon: 'success' })
      user.value.scoreSize++
      classList.value[wallIndex.value] = { ...classList.value[wallIndex.value], userScore: scoringCount.value }
      closeScoringPopup()
    }
    else {
      uni.showToast({ title: '已经评分过了', icon: 'error' })
    }
  },

  )
}
async function downloadHandler() {
  // #ifdef H5

  uni.showModal({
    content: '长按保存壁纸',
    showCancel: false,
  })
  // #endif

  // #ifndef H5
  // loading效果

  uni.showLoading({
    title: '下载中...',
    mask: true,
  })
  getDownloadWallApi({ classid: wallData.value.classid, wallId: wallData.value._id }).then((res) => {
    if (!res) {
      throw new Error('下载失败')
    }
    uni.getImageInfo({
      src: wallData.value.picurl,
      success: (success) => {
        uni.saveImageToPhotosAlbum({
          filePath: success.path,
          success: (success) => {
            uni.showToast({
              title: '保存成功',
            })
            user.value.downloadSize++
          },
          fail: (err) => {
            // 取消保存
            if (err.errMsg === 'saveImageToPhotosAlbum:fail cancel') {
              uni.showToast({
                title: '保存失败',
                icon: 'none',
              })
              return
            }
            // 重新授权
            uni.showModal({
              title: '提示',
              content: '需要授权保存相册',

              success: ({ confirm, cancel }) => {
                if (confirm) {
                  uni.openSetting({
                    success: (setting) => {
                      if (setting.authSetting['scope.writePhotosAlbum']) {
                        uni.showToast({
                          title: '获取授权成功',
                        })
                      }
                      else {
                        uni.showToast({
                          title: '获取授权失败',
                        })
                      }
                    },
                  })
                }
              },

            })
          },

        })
      },

    })
  }).catch((err) => {
    console.log(err, 'catch')

    uni.showToast({ title: err.message, icon: 'error' })
  }).finally(() => {

  })

  // #endif
}
function goBackHandler() {
  uni.navigateBack({
    fail: () => {
      uni.reLaunch({
        url: '/pages/index/index',
      })
    },
  })
}
function classificationHandler() {
  // uni.navigateTo({
  //   url: `/pages/classList/classList?classid=${wallData.value.classid}&classname=${classificationName.value}`,
  // })
}
async function getDetailWall(id: string) {
  classList.value.forEach((item, index) => {
    if (item._id === id) {
      wallIndex.value = index
      wallData.value = classList.value[index]
      item.userScore && (scoringCount.value = item.userScore)
    }
  })
}

onLoad((options) => {
  if (options.type === 'share') {
    // 分享
    classListTotal.value = 1
    classificationName.value = options.classificationName
    getDetailWallApi(options.id).then((res) => {
      if (res) {
        classList.value = res.map((item) => {
          return { ...item, picurl: item.smallPicurl.replace('_small.webp', '.jpg') }
        })
        wallIndex.value = 0
        wallData.value = classList.value[0]
      }
    })
  }
  else {
    // 普通列表页面和user页面
    if (options.type) {
      userType.value = options.type
    }
    getDetailWall(options.id)
  }
})
let wallIndexArr = ref([])
watch(wallIndex, (newVal) => {
  if (!wallIndexArr.value.includes(newVal)) {
    let arr = [newVal - 1, newVal, newVal + 1]
    if (newVal === 0) {
      arr = [newVal, newVal + 1]
    }
    else if (newVal === classListTotal.value) {
      arr = [newVal, newVal - 1]
    }
    wallIndexArr.value.push(arr)
    wallIndexArr.value = [...new Set(wallIndexArr.value)]
    console.log(wallIndex.value + 1, classList.value.length, '111111111118888888')

    if (wallIndex.value + 1 === classList.value.length && wallIndex.value + 1 !== classListTotal.value) {
      if (classList.value.length >= classListTotal.value) {
        classList.value.length = classListTotal.value
      }
      else {
        getWallList()
      }

      arr = [newVal - 1, newVal]
    }
    classList.value[newVal] = ({ ...classList.value[newVal], picurl: classList.value[newVal].smallPicurl.replace('_small.webp', '.jpg') })
    // arr.forEach((item) => {
    //   classList.value[item] = ({ ...classList.value[item], picurl: classList.value[item].smallPicurl.replace('_small.webp', '.jpg') })
    // })
  }
}, { immediate: true })

onShow(() => {

})
// #ifndef H5
onShareAppMessage((e) => {
  // 分享给好友
  return {
    title: `花朵壁纸-${wallData.value.nickname}`,
    path: `/pages/preview/preview?id=${wallData.value._id}&type=share&classificationName=${classificationName.value}`,
  }
})
// 分享朋友圈
onShareTimeline(() => {
  return {
    title: `花朵壁纸-${wallData.value.nickname}`,
    imageUrl: '/static/images/flower.png', // 1比1
    query: `id=${wallData.value._id}&type=share&classificationName=${classificationName.value}`,
  }
})
// #endif
</script>

<template>
  <view class="detailWall relative box-border size-screen" :style="{ height: heightComputed }">
    <uv-swiper
      v-if="classList.length" :list="classList" key-name="picurl" :current="wallIndex" height="100vh"
      :autoplay="false" @click="maskClick" @change="maskChange"
    />
    <view v-if="maskFlag">
      <!-- 日期 -->
      <view class="info-msg" @click.stop="maskClick">
        <uv-tags
          :text="`${wallIndex + 1} / ${classListTotal}`" type="warning" shape="circle" bg-color="#666666"
          border-color="#666666" class="last-mark"
        />
        <view class="py-5px text-46px font-bold">
          {{ getCurrentTime() }}
        </view>
        <view class="text-16px">
          {{ getCurrentDate() }}
        </view>
      </view>
      <!-- 圆角信息盒子 -->
      <view class="info-box">
        <!-- 信息部分 -->
        <view class="info-item" @click="popOpen">
          <uv-icon name="info-circle" size="24" color="#333" />
          <text class="info-text">信息</text>
        </view>

        <!-- 评分部分 -->
        <view class="info-item" @click="scoringHandler">
          <uv-icon name="star" size="24" color="#ff0000" />
          <text class="info-text">{{ wallData.score }}分</text>
        </view>

        <!-- 下载部分 -->
        <view class="info-item" @click.stop="downloadHandler">
          <uv-icon name="download" size="24" color="#409EFF" />
          <text class="info-text">下载</text>
        </view>
      </view>
      <!-- 返回 -->
      <uv-button
        v-if="maskFlag" shape="circle" color="rgba(42, 37, 36,.5)" class="goBack"
        :style="{ top: `${safeAreaInsets.top === 0 ? 20 : safeAreaInsets.top}px`, height: `${capsuleButtonHeight}px` }"
        @click="goBackHandler"
      >
        <uv-icon name="arrow-left" size="16" color="#fff" />
      </uv-button>
    </view>
  </view>
  <!-- 信息弹框 -->
  <uni-popup
    ref="msgPopup" type="bottom" border-radius="10px 10px 0 0" background-color="#fff" animation is-mask-click
    safe-area class="p-10px"
  >
    <uv-row>
      <uv-col span="6" offset="1" text-align="right">
        <view class="title text-18px">
          壁纸信息
        </view>
      </uv-col>
      <uv-col span="1" offset="4" text-align="left">
        <uv-icon class="right-box" name="close" color="#eee" size="24" @click="closePopup" />
      </uv-col>
    </uv-row>
    <uv-row>
      <uv-col span="2" text-align="right">
        <view class="title">
          壁纸id :
        </view>
      </uv-col>
      <uv-col span="10">
        <view>{{ wallData._id }}</view>
      </uv-col>
    </uv-row>
    <uv-row>
      <uv-col span="2" text-align="right">
        <view class="title">
          分类 :
        </view>
      </uv-col>
      <uv-col span="10">
        <view class="color-#7ddd8f" @click="classificationHandler">
          {{ wallData.classname || classificationName }}
        </view>
      </uv-col>
    </uv-row>
    <uv-row>
      <uv-col span="2" text-align="right">
        <view class="title">
          发布者 :
        </view>
      </uv-col>
      <uv-col span="10">
        <view>{{ wallData.nickname }}</view>
      </uv-col>
    </uv-row>

    <uv-row>
      <uv-col span="2" text-align="right">
        <view class="title">
          评分 :
        </view>
      </uv-col>
      <uv-col span="10">
        <view class="flex items-center">
          <uni-rate v-model="wallData.score" :max="5" allow-half disabled />
          <view class="ml-5px">
            {{ wallData.score || '暂无评分' }}
          </view>
        </view>
      </uv-col>
    </uv-row>
    <uv-row>
      <uv-col span="2" text-align="right">
        <view class="title">
          摘要 :
        </view>
      </uv-col>
      <uv-col span="10" class="mr-10px">
        <view class="abstract w-100%">
          <view class="pr-10px">
            {{ wallData.description || '暂无' }}
          </view>
        </view>
      </uv-col>
    </uv-row>
    <uv-row>
      <uv-col span="2" text-align="right">
        <view class="title">
          标签 :
        </view>
      </uv-col>
      <uv-col span="10">
        <view class="flex">
          <uv-tags
            text="标签" plain size="mini" border-color="#21a23a" color="#21a23a" type="success"
            class="mr-4px w-40px"
          />
          <uv-tags
            v-for="(val, index) in wallData.tabs" :key="index" :text="val" plain size="mini" type="success"
            class="mr-4px"
          />
        </view>
      </uv-col>
    </uv-row>
    <uv-row>
      <uv-col span="12">
        <view class="abstract w-100% bg-#eee color-#292424">
          <view class="p-10px">
            声明：本图片来用户投稿，非商业使用，用于免费学习交流，如侵犯了您的权益，您可以拷贝壁纸ID举报至平台，邮箱513894357@qq.com，管理将删除侵权壁纸，维护您的权益。
          </view>
        </view>
      </uv-col>
    </uv-row>
  </uni-popup>
  <!-- 评分弹窗 -->
  <uni-popup
    ref="scoringPopup" type="center" background-color="#fff" animation :is-mask-click="false"
    border-radius="10px" class="scoring"
  >
    <uv-row>
      <uv-col span="6" offset="1" text-align="right">
        <view class="title text-18px">
          {{ isScoreFlag ? '已经评分过了~' : '壁纸评分' }}
        </view>
      </uv-col>
      <uv-col span="1.5" offset="3.5" text-align="left">
        <uv-icon class="right-box" name="close" color="#eee" size="24" @click="closeScoringPopup" />
      </uv-col>
    </uv-row>
    <view class="my-20px flex items-center justify-center">
      <uni-rate v-model="scoringCount" :max="5" allow-half :disabled="isScoreFlag" />
      <text class="pl-8px color-#ffcf4a">{{ scoringCount }}分</text>
    </view>
    <view class="flex justify-center">
      <uv-button
        v-if="!isScoreFlag" type="primary" :plain="true" :disabled="!scoringCount" text="确定评分"
        class="w-80px opacity-80" color="#2b2628" @click="scoringSubmitHandler"
      />
    </view>
  </uni-popup>
</template>

<style lang="scss" scoped>
.scoring {
  :deep(.uni-popup__wrapper) {
    width: 80%;
    padding-bottom: 10px;
  }
}

:deep(.uv-tags) {
  opacity: 0.5;
}

.uv-row {
  margin: 10px;

  .uv-col {
    margin: 0 10px;

    .title {
      color: #827d7d;
      font-size: 14px;
    }
  }

  .abstract {
    overflow-wrap: break-word;
  }
}

.header {
  display: flex;
  align-items: center;

  .placeholder {
    flex: 1;
  }

  .center-box {
    flex: none;
  }

  .right-box {
    flex: 1;
    text-align: right;
  }
}

.detailWall {
  position: relative;

  .goBack {
    position: absolute;
    left: 20px;
  }

  .info-msg {
    position: absolute;
    top: 20vh;
    left: 10vw;
    right: 10vw;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    color: #fff;
    text-align: center;
  }

  .info-box {
    position: absolute;
    bottom: 10vh;
    left: 10vw;
    right: 10vw;
    display: flex;
    justify-content: space-between;
    background-color: rgba(255, 255, 255, 0.9);
    border-radius: 40px;
    padding: 10px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);

    .info-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin: 0 20px;
    }
  }
}
</style>
